package com.fivefox.event.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fivefox.common.configuration.FeiShuAppConfig;
import com.fivefox.event.domain.bo.EventBo;
import com.fivefox.event.domain.bo.WebhookBo;
import com.fivefox.event.service.WebhookService;
import com.fivefox.event.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WebhookServiceImpl implements WebhookService {
    private static final String URL_VERIFICATION = "url_verification";
    private static final String ENCRYPT = "encrypt";
    @Autowired
    private FeiShuAppConfig feiShuAppConfig;

    @Override
    public String callback(String body) throws Exception {
        // 密文，则转为明文
        if (body.contains(ENCRYPT)) {
            WebhookBo webhookBo = JSONUtil.toBean(body, WebhookBo.class);
            body = AESUtil.decrypt(feiShuAppConfig.getEncryptKey(), webhookBo.getEncrypt());
            if (StrUtil.isEmpty(body)) {
                throw new Exception("事件密文解密失败!");
            }
            log.info("事件密文：{}", webhookBo.getEncrypt());
            log.info("事件明文：{}", body);
        }
        // 校验数据
        EventBo eventBo = JSONUtil.toBean(body, EventBo.class);
        if (ObjUtil.isNull(eventBo)) {
            throw new Exception("事件JSON数据转对象为空!");
        }
        // 是否首次订阅事件
        if (URL_VERIFICATION.equals(eventBo.getType())) {
            log.info("首次订阅事件");
            return body;
        }
        return body;
    }
}
